﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Xml.Serialization;


namespace MyXMLPrase
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            listView1.AutoArrange = true;
            dataGridView1.AutoSize = true;
            treeView1.Scrollable = true;
            listView1.Scrollable = true;


        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = Environment.CurrentDirectory;
            openFileDialog1.Filter = "元数据文件(*.xml)|*.xml";
            String fileName;
            XmlDocument xmlDoc = new XmlDocument();
            openFileDialog1.ValidateNames = true;
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    fileName = openFileDialog1.FileName;
                    xmlDoc.Load(fileName);
                    XmlNode xN = xmlDoc.DocumentElement;
                    foreach (XmlNode xNtemp in xN.ParentNode)
                    {
                        TreeNode trerotnod = new TreeNode();
                        trerotnod.Text = xNtemp.Name;
                        treeView1.Nodes.Add(trerotnod);
                        TransXML(xNtemp.ChildNodes, trerotnod);
                    }

                }
                else
                {
                    return;
                }
            }
            catch (Exception eo)
            {
                MessageBox.Show(eo.ToString());
            }

            //删掉一个多余的xml节点.
            try
            {
                treeView1.Nodes.RemoveAt(0);
            }
            catch (Exception ex)
            {
                // MessageBox.Show("XML文件错误，请修改后再打开");
                MessageBox.Show(ex.ToString());
                return;

            }
            //openFileDialog1.Filter = "元数据文件(*.XML)|*.xml";
            //openFileDialog1.InitialDirectory = Environment.CurrentDirectory;
            //try
            //{
            //    XML2TreeNode xml2treenode = new XML2TreeNode();
            //    xml2treenode.Initinal(treeView1,openFileDialog1);

            //}
            //catch
            //{
            //    return;
            //}

        }

       
        private int TransXML(XmlNodeList Xmlnodes, TreeNode partrenod)
        {
            //------遍历XML中的所有节点，仿照treeview节点遍历函数   
            foreach (XmlNode xmlnod in Xmlnodes)
            {
                TreeNode subtrnod = new TreeNode();
                //用If - Else是因为值节点没有结节名字,只有值了.
                if (xmlnod.Name != "#text")
                {
                    subtrnod.Text = xmlnod.Name + xmlnod.Value;
                    if (xmlnod.Attributes.Count > 0)
                    {
                        subtrnod.Text += "(";
                        for (int i = 0; i < xmlnod.Attributes.Count; i++)
                        {
                            subtrnod.Text += xmlnod.Attributes[i].Name;
                            subtrnod.Text += ":";
                            
                            subtrnod.Text += xmlnod.Attributes[i].InnerText;
                            subtrnod.Text += "|";
                        }
                        subtrnod.Text += ")";
                    }
                }
                else
                { 
                    subtrnod.Text = xmlnod.Value;
                }
                partrenod.Nodes.Add(subtrnod);

                if (xmlnod.ChildNodes.Count > 0)
                {
                    TransXML(xmlnod.ChildNodes, subtrnod);
                }
            }
            return 0;
        }
 
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            
            ListViewItem item1 = new ListViewItem();
            item1.Text = treeView1.SelectedNode.Text  ;
            item1.ImageIndex = 0;
            //如果已经存在了这个项,就不插入.
            if (!IsExistsItem(item1.Text))
            {
                listView1.Items.Add(item1);
            }
            else
            {
                foreach (ListViewItem item in listView1.Items)
                {
                    item.ImageIndex = 0;
                      
                }
               listView1.FindItemWithText(item1.Text).Focused = true;
               listView1.FocusedItem.ImageIndex = 1;
               
            }

    


        }

        //判断listview1里是不是已经存在了Item
        private bool IsExistsItem(string text)
        {
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.Text == text)
                    return true;
            }
            return false;
        }

        private void openurl(object sender, EventArgs e)
        {
            String url;
            url = "http://sse.ustc.edu.cn";
            System.Diagnostics.Process.Start(url);

        }

        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.Visible = true;
        }

        private void 更新UToolStripMenuItem_Click(object sender, EventArgs e)
        {
            return;
        }

        private void 复制CToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 撤销UToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void 导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void TreeNode2Xml(TreeNodeCollection treeNodes, XmlNode xmlNode)
        {
            XmlDocument doc = xmlNode.OwnerDocument;
            foreach (TreeNode treeNode in treeNodes)
            {
                XmlNode element = doc.CreateNode("element", "Item", "");
                XmlAttribute attr = doc.CreateAttribute("Title");
                attr.Value = treeNode.Text;
                element.Attributes.Append(attr);
                element.AppendChild(doc.CreateCDataSection(treeNode.Tag.ToString()));
                xmlNode.AppendChild(element);

                if (treeNode.Nodes.Count > 0)
                {
                    TreeNode2Xml(treeNode.Nodes, element);
                }
            }
        }
        private void 导出EToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.FileName ="导出XML文件"+ DateTime.Now.ToShortDateString().ToString().Replace("/", "").Replace(" ", "") + ".xml";
            sfd.Filter = "元数据文件(*.xml)|*.xml|所有文件(*.*)|*.*";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    //String filepath = sfd.FileName;
                    //TreeView2XML tv = new TreeView2XML();
                    //tv.TreeToXML(treeView1, sfd.FileName);
                   // TreeNode2Xml(treeView1, sfd.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存文件遇到问题","提示");
                    return;
                }

            }
        }

        private void 粘帖PToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 剪贴XToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 重做RToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 关键字KToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SearchTreeByKey stb = new SearchTreeByKey();
            stb.Visible = true;
        }

        private void 节点NToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 值VToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 文件FToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            String key;
            key = "It is a test for XML DBMS";
            System.Diagnostics.Process.Start("http://www.baidu.com/s?wd=" + key);
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc");
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer");
        }

        private void 打开OToolStripButton_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = Environment.CurrentDirectory;
            openFileDialog1.Filter = "元数据文件(*.xml)|*.xml|所有文件(*.*)|*.*";
            String fileName;
            XmlDocument xmlDoc = new XmlDocument();
            openFileDialog1.ValidateNames = true;
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    fileName = openFileDialog1.FileName;
                    xmlDoc.Load(fileName);
                    XmlNode xN = xmlDoc.DocumentElement;
                    foreach (XmlNode xNtemp in xN.ParentNode)
                    {
                        TreeNode trerotnod = new TreeNode();
                        trerotnod.Text = xNtemp.Name;
                        treeView1.Nodes.Add(trerotnod);
                        TransXML(xNtemp.ChildNodes, trerotnod);
                    }

                }
            }
            catch (Exception eo)
            {
                MessageBox.Show(eo.ToString());
            }

            //删掉一个多余的xml节点.
            try
            {
                treeView1.Nodes.RemoveAt(0);
            }
            catch (Exception ex)
            {
               // MessageBox.Show(ex.ToString());
               // MessageBox.Show("XML文件错误，请修改后再打开");
                return;
            }
            
        }

        private void 保存SToolStripButton_Click(object sender, EventArgs e)
        {
            MessageBox.Show("保存成功","提示");
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (dataGridView1.ReadOnly == false)
            {
                dataGridView1.ReadOnly = true;
                toolStripButton4.ToolTipText = "解锁";
            }
            else
            {
                dataGridView1.ReadOnly = false;
                toolStripButton4.ToolTipText = "加锁";
            }
        }

        private void listViewNodeDoubleClick(object sender, MouseEventArgs e)
        {
            dataGridView1.Rows.Clear();
            dataGridView1.Update();
            //判断是不是有属性,如果有,则找出来,如果没有.就直接在datagridvie里面输出 .
            try
            {
                if (listView1.FocusedItem.Text.Contains("("))
                {
                    String str = listView1.FocusedItem.Text;
                    int length = str.Length;
                    //用subAttNumber来表示有几个属性值.一个属性对应一个subAttNumber.
                    int subAttNumber = 0;
                    foreach (char c in str)
                    {
                        if (c.Equals('|'))
                            subAttNumber++;
                    }
                    String head = str.Substring(0, str.IndexOf("("));
                    String nameValue = head.Substring(0, head.IndexOf(":"));
                    dataGridView1.Columns[0].HeaderText = nameValue;
                    nameValue = nameValue + ":";
                    dataGridView1.Rows[0].Cells[0].Value = head.Replace(nameValue, "");
                    str = str.Replace(head, "");
                    str = str.Replace("(", "");
                    // MessageBox.Show(str);
                    for (int i = 0; i < subAttNumber; i++)
                    {

                        String temp = str.Substring(0, str.IndexOf("|"));
                        nameValue = temp.Substring(0, temp.IndexOf(":"));
                        dataGridView1.Columns[i + 1].HeaderText = nameValue;
                        nameValue = nameValue + ":";
                        temp = temp.Replace(nameValue, "");
                        dataGridView1.Rows[0].Cells[i + 1].Value = temp;
                        temp = temp + "|";
                        str = str.Replace(temp, "");
                    }
                }
                else
                {
                    String temp1 = listView1.FocusedItem.Text.ToString();
                    String temp2 = temp1.Substring(0, temp1.IndexOf(":"));
                    dataGridView1.Columns[0].HeaderText = temp2;
                    temp2 = temp2 + ":";
                    temp1 = temp1.Replace(temp2, "");
                    dataGridView1.Rows.Add(temp1);
                }
            }catch(Exception ex)
            {
                return;
             }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            
        }

        private void 帮助LToolStripButton_Click(object sender, EventArgs e)
        {
            MessageBox.Show("暂时没有添加帮助信息");
        }

        private void clickLeftAndRight(object sender, EventArgs e)
        {
            
        }

        //修正了鼠标事件,点击右键鼠标,弹出菜单.位置正确了,不选择的话,不显示菜单.
        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                if (e.Button == MouseButtons.Right)
                {
                    listViewPopMenu.Show(this.listView1,e.Location);
                }
            }
        }

        private void deleteNode_Click(object sender, EventArgs e)
        {
            if (listView1.FocusedItem == null)
            {
                return;
            }
            else
            {

                listView1.FocusedItem.Remove();
            }
        }

        private void editNode_Click(object sender, EventArgs e)
        {
            if (listView1.FocusedItem == null)
            {
                return;
            }
            else
            {

                listView1.FocusedItem.BeginEdit();
            }
        }

        private void pasteNode_Click(object sender, EventArgs e)
        {
            MessageBox.Show("粘帖");
        }

        private void refresh_Click(object sender, EventArgs e)
        {
            listView1.Refresh();
        }

        private void copyNode_Click(object sender, EventArgs e)
        {
            MessageBox.Show("copy success");
        }

        private void 验证XML文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            if (of.ShowDialog() == DialogResult.OK)
            {
                ValidateXML myValidationReadingXMLSample = new ValidateXML();
                myValidationReadingXMLSample.Run(of.FileName);
                //ValidateXMLInfomationDisplay vd = new ValidateXMLInfomationDisplay();
                //vd.Visible = true;
                //try
                //{
                //    vd.richTextBox1.Text += "\n\nFinished\n\n";
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.ToString());
                //}

                Console.ReadLine();
            }
        }

        private void 打开XMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "元数据文件(*.xml)|*.xml";
            openFileDialog1.InitialDirectory = ".";
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {

                Form3 f3 = new Form3();
                f3.webBrowser1.Navigate(openFileDialog1.FileName);
                f3.Show();
            }
        }

        private void changeValue(object sender, EventArgs e)
        {
            ChangeValueOfNode cvn = new ChangeValueOfNode();
            cvn.Show();
        }

        private void changeNode_Click(object sender, EventArgs e)
        {
            ChangeValueOfNode cvn = new ChangeValueOfNode();
            cvn.Show();
        }

    }
}
